<template>
  <div class="customer-list-container">
    <!-- 页面标题 -->
    <div class="page-header">
      <div class="page-title">客户列表</div>
      <el-button type="primary" icon="el-icon-plus" @click="showAddCustomerDialog">添加客户</el-button>
    </div>

    <!-- 搜索和筛选 -->
    <div class="search-filter-container">
      <el-card shadow="hover">
        <el-form :inline="true" :model="searchForm" class="search-form">
          <el-form-item label="客户ID">
            <el-input v-model="searchForm.customerId" placeholder="请输入客户ID" clearable></el-input>
          </el-form-item>
          <el-form-item label="合同类型">
            <el-select v-model="searchForm.contract" placeholder="全部" clearable>
              <el-option label="月付" value="Month-to-month"></el-option>
              <el-option label="一年期" value="One year"></el-option>
              <el-option label="两年期" value="Two year"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="互联网服务">
            <el-select v-model="searchForm.internetService" placeholder="全部" clearable>
              <el-option label="无" value="No"></el-option>
              <el-option label="DSL" value="DSL"></el-option>
              <el-option label="光纤" value="Fiber optic"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="流失风险">
            <el-select v-model="searchForm.riskLevel" placeholder="全部" clearable>
              <el-option label="低风险" value="low"></el-option>
              <el-option label="中风险" value="medium"></el-option>
              <el-option label="高风险" value="high"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="handleSearch">搜索</el-button>
            <el-button @click="resetSearch">重置</el-button>
          </el-form-item>
        </el-form>
      </el-card>
    </div>

    <!-- 数据表格 -->
    <div class="customer-table-container">
      <el-card shadow="hover">
        <template #header>
          <div class="card-header">
            <span>客户数据列表</span>
            <div class="header-operations">
              <el-button size="small" icon="el-icon-download">导出</el-button>
              <el-button size="small" icon="el-icon-refresh" @click="fetchCustomers">刷新</el-button>
            </div>
          </div>
        </template>
        
        <el-table
          v-loading="loading"
          :data="customers"
          border
          stripe
          style="width: 100%"
          highlight-current-row
          @row-click="handleRowClick"
        >
          <el-table-column prop="customer_id" label="客户ID" width="120"></el-table-column>
          <el-table-column prop="gender_display" label="性别" width="80"></el-table-column>
          <el-table-column prop="senior_citizen" label="老年客户" width="100">
            <template #default="scope">
              {{ scope.row.senior_citizen ? '是' : '否' }}
            </template>
          </el-table-column>
          <el-table-column prop="tenure" label="使用时长(月)" width="120"></el-table-column>
          <el-table-column prop="contract" label="合同类型" width="120">
            <template #default="scope">
              <el-tag v-if="scope.row.contract === 'Month-to-month'" type="info">月付</el-tag>
              <el-tag v-else-if="scope.row.contract === 'One year'" type="success">一年期</el-tag>
              <el-tag v-else-if="scope.row.contract === 'Two year'" type="primary">两年期</el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="internet_service" label="互联网服务" width="120">
            <template #default="scope">
              <el-tag v-if="scope.row.internet_service === 'No'" type="info">无</el-tag>
              <el-tag v-else-if="scope.row.internet_service === 'DSL'" type="success">DSL</el-tag>
              <el-tag v-else-if="scope.row.internet_service === 'Fiber optic'" type="primary">光纤</el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="phone_service" label="电话服务" width="100">
            <template #default="scope">
              {{ scope.row.phone_service ? '是' : '否' }}
            </template>
          </el-table-column>
          <el-table-column prop="monthly_charges" label="月费用" width="120">
            <template #default="scope">
              ¥{{ Number(scope.row.monthly_charges).toFixed(2) }}
            </template>
          </el-table-column>
          <el-table-column prop="churn" label="是否流失" width="100">
            <template #default="scope">
              <el-tag v-if="scope.row.churn" type="danger">是</el-tag>
              <el-tag v-else type="success">否</el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="churn_risk" label="流失风险" width="120">
            <template #default="scope">
              <el-tag v-if="scope.row.churn_risk === 'low'" type="success">低风险</el-tag>
              <el-tag v-else-if="scope.row.churn_risk === 'medium'" type="warning">中风险</el-tag>
              <el-tag v-else-if="scope.row.churn_risk === 'high'" type="danger">高风险</el-tag>
              <span v-else>未评估</span>
            </template>
          </el-table-column>
          <el-table-column label="操作" fixed="right" width="250">
            <template #default="scope">
              <el-button size="mini" @click.stop="viewCustomerDetail(scope.row)">查看</el-button>
              <el-button size="mini" type="primary" @click.stop="predictCustomerChurn(scope.row)">预测</el-button>
              <el-button size="mini" type="danger" @click.stop="handleDelete(scope.row)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>

        <!-- 分页 -->
        <div class="pagination-container">
          <el-pagination
            background
            layout="total, sizes, prev, pager, next, jumper"
            :current-page="pagination.currentPage"
            :page-sizes="[10, 20, 50, 100]"
            :page-size="pagination.pageSize"
            :total="pagination.total"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
          >
          </el-pagination>
        </div>
      </el-card>
    </div>
  </div>

  <!-- 添加客户对话框 -->
  <el-dialog
    title="添加新客户"
    v-model="addCustomerDialogVisible"
    width="650px"
    :close-on-click-modal="false"
  >
    <el-form
      ref="customerForm"
      :model="customerFormData"
      :rules="customerFormRules"
      label-width="120px"
      :disabled="formLoading"
    >
      <!-- 基本信息 -->
      <h4>基本信息</h4>
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="客户ID" prop="customer_id">
            <el-input v-model="customerFormData.customer_id" placeholder="输入客户ID"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="性别" prop="gender">
            <el-radio-group v-model="customerFormData.gender">
              <el-radio label="Male">男</el-radio>
              <el-radio label="Female">女</el-radio>
            </el-radio-group>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="老年客户" prop="senior_citizen">
            <el-switch
              v-model="customerFormData.senior_citizen"
              active-text="是"
              inactive-text="否"
            ></el-switch>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="伴侣" prop="partner">
            <el-switch
              v-model="customerFormData.partner"
              active-text="有"
              inactive-text="无"
            ></el-switch>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="家庭成员" prop="dependents">
            <el-switch
              v-model="customerFormData.dependents"
              active-text="有"
              inactive-text="无"
            ></el-switch>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="使用时长(月)" prop="tenure">
            <el-input-number v-model="customerFormData.tenure" :min="0" :max="72" style="width: 100%"></el-input-number>
          </el-form-item>
        </el-col>
      </el-row>

      <!-- 服务信息 -->
      <h4>服务信息</h4>
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="电话服务" prop="phone_service">
            <el-switch
              v-model="customerFormData.phone_service"
              active-text="有"
              inactive-text="无"
            ></el-switch>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="多线服务" prop="multiple_lines">
            <el-select v-model="customerFormData.multiple_lines" placeholder="请选择" style="width: 100%">
              <el-option label="无" value="No"></el-option>
              <el-option label="有" value="Yes"></el-option>
              <el-option label="无电话服务" value="No phone service"></el-option>
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="互联网服务" prop="internet_service">
            <el-select v-model="customerFormData.internet_service" placeholder="请选择" style="width: 100%">
              <el-option label="无" value="No"></el-option>
              <el-option label="DSL" value="DSL"></el-option>
              <el-option label="光纤" value="Fiber optic"></el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="在线安全" prop="online_security">
            <el-select v-model="customerFormData.online_security" placeholder="请选择" style="width: 100%">
              <el-option label="无" value="No"></el-option>
              <el-option label="有" value="Yes"></el-option>
              <el-option label="无互联网服务" value="No internet service"></el-option>
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="在线备份" prop="online_backup">
            <el-select v-model="customerFormData.online_backup" placeholder="请选择" style="width: 100%">
              <el-option label="无" value="No"></el-option>
              <el-option label="有" value="Yes"></el-option>
              <el-option label="无互联网服务" value="No internet service"></el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="设备保护" prop="device_protection">
            <el-select v-model="customerFormData.device_protection" placeholder="请选择" style="width: 100%">
              <el-option label="无" value="No"></el-option>
              <el-option label="有" value="Yes"></el-option>
              <el-option label="无互联网服务" value="No internet service"></el-option>
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="技术支持" prop="tech_support">
            <el-select v-model="customerFormData.tech_support" placeholder="请选择" style="width: 100%">
              <el-option label="无" value="No"></el-option>
              <el-option label="有" value="Yes"></el-option>
              <el-option label="无互联网服务" value="No internet service"></el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="流媒体电视" prop="streaming_tv">
            <el-select v-model="customerFormData.streaming_tv" placeholder="请选择" style="width: 100%">
              <el-option label="无" value="No"></el-option>
              <el-option label="有" value="Yes"></el-option>
              <el-option label="无互联网服务" value="No internet service"></el-option>
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="流媒体电影" prop="streaming_movies">
            <el-select v-model="customerFormData.streaming_movies" placeholder="请选择" style="width: 100%">
              <el-option label="无" value="No"></el-option>
              <el-option label="有" value="Yes"></el-option>
              <el-option label="无互联网服务" value="No internet service"></el-option>
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>

      <!-- 合同信息 -->
      <h4>合同信息</h4>
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="合同类型" prop="contract">
            <el-select v-model="customerFormData.contract" placeholder="请选择" style="width: 100%">
              <el-option label="月付" value="Month-to-month"></el-option>
              <el-option label="一年期" value="One year"></el-option>
              <el-option label="两年期" value="Two year"></el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="电子账单" prop="paperless_billing">
            <el-switch
              v-model="customerFormData.paperless_billing"
              active-text="是"
              inactive-text="否"
            ></el-switch>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="支付方式" prop="payment_method">
            <el-select v-model="customerFormData.payment_method" placeholder="请选择" style="width: 100%">
              <el-option label="电子支票" value="Electronic check"></el-option>
              <el-option label="邮寄支票" value="Mailed check"></el-option>
              <el-option label="银行转账(自动)" value="Bank transfer (automatic)"></el-option>
              <el-option label="信用卡(自动)" value="Credit card (automatic)"></el-option>
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>

      <!-- 费用信息 -->
      <h4>费用信息</h4>
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="月费用" prop="monthly_charges">
            <el-input-number v-model="customerFormData.monthly_charges" :min="0" :precision="2" :step="0.01" style="width: 100%"></el-input-number>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="总费用" prop="total_charges">
            <el-input-number 
              v-model="customerFormData.total_charges" 
              :min="0" 
              :precision="2" 
              :step="0.01" 
              style="width: 100%" 
              :disabled="autoCalculateTotalCharges"
            ></el-input-number>
            <div class="auto-calculate-hint">
              <el-checkbox v-model="autoCalculateTotalCharges">自动计算 (月费用 × 使用时长)</el-checkbox>
            </div>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="addCustomerDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitCustomerForm" :loading="formLoading">提交</el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script setup>
import { ref, reactive, onMounted, watch } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { getCustomerList, deleteCustomer, createCustomer } from '@/api/modules/customer'
import { predictCustomerById as predictChurn } from '@/api/modules/prediction'

// 搜索表单数据
const searchForm = reactive({
  customerId: '',
  contract: '',
  internetService: '',
  riskLevel: ''
})

// 客户数据
const customers = ref([])
const loading = ref(false)

// 分页配置
const pagination = reactive({
  currentPage: 1,
  pageSize: 10,
  total: 0
})

// 添加客户对话框相关
const addCustomerDialogVisible = ref(false)
const customerForm = ref(null)
const customerFormData = reactive({
  customer_id: '',
  gender: 'Male',
  senior_citizen: false,
  partner: false,
  dependents: false,
  tenure: 0,
  phone_service: false,
  multiple_lines: 'No',
  internet_service: 'No',
  online_security: 'No',
  online_backup: 'No',
  device_protection: 'No',
  tech_support: 'No',
  streaming_tv: 'No',
  streaming_movies: 'No',
  contract: 'Month-to-month',
  paperless_billing: false,
  payment_method: 'Electronic check',
  monthly_charges: 0,
  total_charges: 0
})
const customerFormRules = reactive({
  customer_id: [{ required: true, message: '请输入客户ID', trigger: 'blur' }],
  gender: [{ required: true, message: '请选择性别', trigger: 'change' }],
  senior_citizen: [{ type: 'boolean', required: true, message: '请选择是否为老年客户', trigger: 'change' }],
  partner: [{ type: 'boolean', required: true, message: '请选择是否有伴侣', trigger: 'change' }],
  dependents: [{ type: 'boolean', required: true, message: '请选择是否有家庭成员', trigger: 'change' }],
  tenure: [{ required: true, message: '请输入使用时长', trigger: 'blur', type: 'number', min: 0 }],
  phone_service: [{ type: 'boolean', required: true, message: '请选择是否提供电话服务', trigger: 'change' }],
  multiple_lines: [{ required: true, message: '请选择多线服务', trigger: 'change' }],
  internet_service: [{ required: true, message: '请选择互联网服务', trigger: 'change' }],
  online_security: [{ required: true, message: '请选择在线安全', trigger: 'change' }],
  online_backup: [{ required: true, message: '请选择在线备份', trigger: 'change' }],
  device_protection: [{ required: true, message: '请选择设备保护', trigger: 'change' }],
  tech_support: [{ required: true, message: '请选择技术支持', trigger: 'change' }],
  streaming_tv: [{ required: true, message: '请选择流媒体电视', trigger: 'change' }],
  streaming_movies: [{ required: true, message: '请选择流媒体电影', trigger: 'change' }],
  contract: [{ required: true, message: '请选择合同类型', trigger: 'change' }],
  paperless_billing: [{ type: 'boolean', required: true, message: '请选择是否为电子账单', trigger: 'change' }],
  payment_method: [{ required: true, message: '请选择支付方式', trigger: 'change' }],
  monthly_charges: [{ required: true, message: '请输入月费用', trigger: 'blur', type: 'number', min: 0 }],
  total_charges: [{ required: true, message: '请输入总费用', trigger: 'blur', type: 'number', min: 0 }]
})
const formLoading = ref(false)

// 自动计算总费用
const autoCalculateTotalCharges = ref(true)

// 监听月费用和使用时长变化，自动计算总费用
watch([() => customerFormData.monthly_charges, () => customerFormData.tenure, () => autoCalculateTotalCharges.value], () => {
  if (autoCalculateTotalCharges.value) {
    customerFormData.total_charges = Number((customerFormData.monthly_charges * customerFormData.tenure).toFixed(2))
  }
})

// 监听互联网服务变化
watch(() => customerFormData.internet_service, (newValue) => {
  if (newValue === 'No') {
    // 如果没有互联网服务，则将相关服务设为"无互联网服务"
    customerFormData.online_security = 'No internet service'
    customerFormData.online_backup = 'No internet service'
    customerFormData.device_protection = 'No internet service'
    customerFormData.tech_support = 'No internet service'
    customerFormData.streaming_tv = 'No internet service'
    customerFormData.streaming_movies = 'No internet service'
  } else if (newValue === 'DSL' || newValue === 'Fiber optic') {
    // 如果有互联网服务，则将之前设为"无互联网服务"的选项改为"否"
    if (customerFormData.online_security === 'No internet service') customerFormData.online_security = 'No'
    if (customerFormData.online_backup === 'No internet service') customerFormData.online_backup = 'No'
    if (customerFormData.device_protection === 'No internet service') customerFormData.device_protection = 'No'
    if (customerFormData.tech_support === 'No internet service') customerFormData.tech_support = 'No'
    if (customerFormData.streaming_tv === 'No internet service') customerFormData.streaming_tv = 'No'
    if (customerFormData.streaming_movies === 'No internet service') customerFormData.streaming_movies = 'No'
  }
})

// 监听电话服务变化
watch(() => customerFormData.phone_service, (newValue) => {
  if (!newValue) {
    // 如果没有电话服务，则将多线业务设为"无电话服务"
    customerFormData.multiple_lines = 'No phone service'
  } else if (customerFormData.multiple_lines === 'No phone service') {
    // 如果有电话服务，且多线业务为"无电话服务"，则设为"否"
    customerFormData.multiple_lines = 'No'
  }
})

// 获取客户数据
const fetchCustomers = async () => {
  loading.value = true
  try {
    const params = {
      page: pagination.currentPage,
      page_size: pagination.pageSize,
      customer_id: searchForm.customerId,
      contract: searchForm.contract,
      internet_service: searchForm.internetService,
      risk_level: searchForm.riskLevel
    }

    const response = await getCustomerList(params)
    console.log('API响应数据:', response) // 调试日志
    
    if (response.success) {
      // 直接使用response中的results和count
      customers.value = response.results || []
      pagination.total = response.count || 0
    } else {
      ElMessage.error(response.message || '获取客户列表失败')
    }
  } catch (error) {
    console.error('获取客户列表错误:', error)
    ElMessage.error('网络错误，请稍后重试')
  } finally {
    loading.value = false
  }
}

// 搜索处理
const handleSearch = () => {
  pagination.currentPage = 1
  fetchCustomers()
}

// 重置搜索条件
const resetSearch = () => {
  Object.keys(searchForm).forEach(key => {
    searchForm[key] = ''
  })
  pagination.currentPage = 1
  fetchCustomers()
}

// 分页大小变化
const handleSizeChange = (size) => {
  pagination.pageSize = size
  fetchCustomers()
}

// 当前页码变化
const handleCurrentChange = (page) => {
  pagination.currentPage = page
  fetchCustomers()
}

// 行点击事件
const handleRowClick = (row) => {
  viewCustomerDetail(row)
}

// 查看客户详情
const viewCustomerDetail = (row) => {
  console.log('跳转到客户详情页面:', row.customer_id);

  const targetUrl = `/customer/detail/${row.customer_id}`;

  // 使用window.location.href强制页面刷新跳转
  // 这样可以避免Vue Router的组件复用问题
  window.location.href = targetUrl;
}

// 预测客户流失
const predictCustomerChurn = async (row) => {
  try {
    ElMessage({
      message: `正在为客户 ${row.customer_id} 进行流失预测分析...`,
      type: 'info'
    })
    
    console.log('发送预测请求，客户ID:', row.customer_id)
    const response = await predictChurn(row.customer_id)
    console.log('预测API响应:', response)
    
    if (response && response.success) {
      // 显示详细的预测结果
      const data = response.data || {}
      const probability = data.probability ? (data.probability * 100).toFixed(2) + '%' : '未知'
      const riskLevel = data.risk_level ? {
        'low': '低风险',
        'medium': '中风险', 
        'high': '高风险'
      }[data.risk_level] : '未知'
      
      ElMessage.success(`预测完成：流失概率 ${probability}，风险等级 ${riskLevel}`)
      
      // 短暂延迟后刷新列表，确保后端更新已完成
      setTimeout(() => {
        fetchCustomers() // 刷新列表以显示最新预测结果
      }, 500)
    } else {
      ElMessage.error(response?.message || '预测失败')
    }
  } catch (error) {
    console.error('预测请求错误:', error)
    ElMessage.error('预测请求发生错误，请稍后重试')
  }
}

// 删除客户
const handleDelete = (row) => {
  ElMessageBox.confirm(`确定要删除客户 ${row.customer_id} 吗？`, '警告', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    try {
      const response = await deleteCustomer(row.customer_id)
      if (response.success) {
        ElMessage.success('删除成功')
        fetchCustomers()
      } else {
        ElMessage.error(response.message || '删除失败')
      }
    } catch (error) {
      console.error('删除请求错误:', error)
      ElMessage.error('删除请求发生错误，请稍后重试')
    }
  }).catch(() => {
    ElMessage.info('已取消删除')
  })
}

// 显示添加客户对话框
const showAddCustomerDialog = () => {
  customerFormData.customer_id = '' // 清空客户ID
  customerFormData.gender = 'Male'
  customerFormData.senior_citizen = false
  customerFormData.partner = false
  customerFormData.dependents = false
  customerFormData.tenure = 0
  customerFormData.phone_service = false
  customerFormData.multiple_lines = 'No'
  customerFormData.internet_service = 'No'
  customerFormData.online_security = 'No'
  customerFormData.online_backup = 'No'
  customerFormData.device_protection = 'No'
  customerFormData.tech_support = 'No'
  customerFormData.streaming_tv = 'No'
  customerFormData.streaming_movies = 'No'
  customerFormData.contract = 'Month-to-month'
  customerFormData.paperless_billing = false
  customerFormData.payment_method = 'Electronic check'
  customerFormData.monthly_charges = 0
  customerFormData.total_charges = 0
  addCustomerDialogVisible.value = true
}

// 提交添加客户表单
const submitCustomerForm = async () => {
  if (!customerForm.value) return
  
  try {
    // 验证表单
    await customerForm.value.validate()
    
    // 设置loading状态
    formLoading.value = true
    
    // 准备提交数据，确保布尔值正确
    const submitData = {...customerFormData}
    
    // 发送请求
    console.log('提交客户数据:', submitData)
    const response = await createCustomer(submitData)
    console.log('服务器响应:', response)
    
    // 处理响应
    if (response && response.success) {
      // 基本成功消息
      ElMessage.success('客户添加成功')
      
      // 获取添加的客户数据
      const customerData = response.data
      
      // 如果客户有流失风险评估且风险较高，给出更详细的提示
      if (customerData.churn_risk && (customerData.churn_risk === 'high' || customerData.churn_risk === 'medium')) {
        const riskLevel = customerData.churn_risk === 'high' ? '高风险' : '中风险'
        const probability = customerData.churn_probability ? `${(customerData.churn_probability * 100).toFixed(1)}%` : '未知'
        
        ElMessageBox.alert(
          `该客户被评估为${riskLevel}流失客户（流失概率: ${probability}）。\n系统已自动创建预警，请前往预警管理页面查看详情。`,
          '客户流失风险提示',
          {
            confirmButtonText: '我知道了',
            type: 'warning',
          }
        )
      }
      
      addCustomerDialogVisible.value = false
      fetchCustomers() // 刷新列表
    } else {
      // 显示错误信息
      if (response && response.message) {
        if (typeof response.message === 'string') {
          ElMessage.error(response.message)
        } else if (typeof response.message === 'object') {
          // 处理验证错误对象
          const errorMessages = Object.entries(response.message)
            .map(([key, errors]) => `${key}: ${Array.isArray(errors) ? errors.join(', ') : errors}`)
            .join('\n')
          ElMessage.error(`提交失败，请修正以下错误:\n${errorMessages}`)
        }
      } else {
        ElMessage.error('客户添加失败，服务器没有返回详细信息')
      }
    }
  } catch (error) {
    if (error.name === 'ValidationError') {
      console.error('表单验证失败:', error)
      ElMessage.warning('表单验证失败，请检查输入')
    } else {
      console.error('添加客户请求错误:', error)
      ElMessage.error('添加客户请求发生错误，请稍后重试')
    }
  } finally {
    formLoading.value = false
  }
}

// 生命周期钩子
onMounted(() => {
  fetchCustomers()
})
</script>

<style lang="scss" scoped>
.customer-list-container {
  padding: 20px;
  
  .page-header {
    display: flex;
    justify-content: space-between;
    margin-bottom: 20px;
    align-items: center;
    
    .page-title {
      font-size: 22px;
      font-weight: bold;
    }
  }
  
  .search-filter-container {
    margin-bottom: 20px;
  }
  
  .customer-table-container {
    .card-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
    }
    
    .pagination-container {
      margin-top: 20px;
      display: flex;
      justify-content: flex-end;
    }
  }
}

.auto-calculate-hint {
  margin-top: 5px;
  font-size: 12px;
  color: #909399;
}

h4 {
  margin-top: 20px;
  margin-bottom: 10px;
  padding-bottom: 5px;
  border-bottom: 1px solid #ebeef5;
  color: #409EFF;
  font-weight: bold;
}
</style> 